package com.example.smartclassroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.smartclassroom.entity.Admin;
import com.example.smartclassroom.entity.Student;
import com.example.smartclassroom.entity.Teacher;
import com.example.smartclassroom.entity.dto.LoginDTO;
import com.example.smartclassroom.entity.dto.UserInfoDTO;
import com.example.smartclassroom.entity.form.LoginForm;
import com.example.smartclassroom.entity.form.RegisterForm;
import com.example.smartclassroom.enums.BorrowStatusEnum;
import com.example.smartclassroom.enums.UserType;
import com.example.smartclassroom.service.LogInService;
import com.example.smartclassroom.util.JsonDate;
import com.example.smartclassroom.util.Jwtutils;
import com.example.smartclassroom.util.LoginUserInfoUtils;
import com.example.smartclassroom.util.MD5;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 登录服务
 */
@Service
@AllArgsConstructor
public class LogInServiceImpl implements LogInService {

    /**
     * 管理员服务
     */
    private AdminServiceImpl adminServiceImpl;
    /**
     * 学生服务
     */
    private StudentSeiveceImpl studentSeiveceImpl;
    /**
     * 教师服务
     */
    private TeacherSeiveceImpl teacherSeiveceImpl;


    /**
     * 登录
     * @param loginForm 登录对象
     * @return
     */
    @Override
    public String login(LoginForm loginForm) {
        //用户密码加密
        String encryptedPassword = MD5.encrypt(loginForm.getPassword());
        loginForm.setPassword(encryptedPassword);
        LoginDTO loginDTO = new LoginDTO();
        UserType userType = UserType.getUserType(loginForm.getUserType());
        //用户登录返回对象
        switch (userType) {
            case ADMIN:
                Admin admin = adminServiceImpl.login(loginForm);
                loginDTO.setLoginId(admin.getId());
                loginDTO.setUserName(admin.getUsername());
                loginDTO.setUserType(userType);
                return Jwtutils.setToken(loginDTO);
            case STUDENT:
                Student student = studentSeiveceImpl.login(loginForm);
                loginDTO.setLoginId(student.getId());
                loginDTO.setUserName(student.getUsername());
                loginDTO.setUserType(userType);
                return Jwtutils.setToken(loginDTO);
            case TEACHER:
                Teacher teacher = teacherSeiveceImpl.login(loginForm);
                loginDTO.setLoginId(teacher.getId());
                loginDTO.setUserName(teacher.getUsername());
                loginDTO.setUserType(userType);
                return Jwtutils.setToken(loginDTO);
            default:
                throw new RuntimeException("错误类型");

        }
    }

    /**
     * 注册
     *
     * @param registerForm 注册对象
     * @return
     */
    @Override
    @Transactional
    public JsonDate register(RegisterForm registerForm) {
        //判断用户名是否是8到10位正则表达式
        if (!registerForm.getUsername().matches("^[0-9]{8,10}$")) {
            return JsonDate.errorEnum(BorrowStatusEnum.REGISTER_USERNAME_ERROR);
        }
        //判断密码是否为6到11位的数字、字母
        if (!registerForm.getPassword().matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,11}$")) {
            return JsonDate.errorEnum(BorrowStatusEnum.REGISTER_PASSWORD_ERROR_FORMAT);
        }

        //判断用户类型
        if (registerForm.getUserType() == null || registerForm.getUserType() == 0) {
            return JsonDate.errorEnum(BorrowStatusEnum.REGISTER_USER_TYPE_NULL);
        }
        //判断密码是否相同
        if (!registerForm.getPassword().equals(registerForm.getConfirmPassword())) {
            return JsonDate.errorEnum(BorrowStatusEnum.REGISTER_PASSWORD_ERROR);
        }
        //判断用户名是否重复
        if (UserType.ADMIN == UserType.getUserType(registerForm.getUserType())) {
            QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", registerForm.getUsername());
            queryWrapper.last("LIMIT 1"); // 添加limit限制
            Admin admin = adminServiceImpl.getOne(queryWrapper);
            if (admin != null) {
                return JsonDate.errorEnum(BorrowStatusEnum.REGISTER_USERNAME_EXIST);
            }
        } else if (UserType.STUDENT == UserType.getUserType(registerForm.getUserType())) {
            QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", registerForm.getUsername());
            queryWrapper.last("LIMIT 1"); // 添加limit限制
            Student student = studentSeiveceImpl.getOne(queryWrapper);
            if (student != null) {
                return JsonDate.errorEnum(BorrowStatusEnum.REGISTER_USERNAME_EXIST);
            }
        }
        if (UserType.TEACHER == UserType.getUserType(registerForm.getUserType())) {
            QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", registerForm.getUsername());
            queryWrapper.last("LIMIT 1"); // 添加limit限制
            Teacher teacher = teacherSeiveceImpl.getOne(queryWrapper);
            if (teacher != null) {
                return JsonDate.errorEnum(BorrowStatusEnum.REGISTER_USERNAME_EXIST);
            }
        }
        //密码加密
        String encryptedPassword = MD5.encrypt(registerForm.getPassword());
        //用户类型
        UserType userType = UserType.getUserType(registerForm.getUserType());
        LoginForm loginForm = new LoginForm();
        //对象拷贝
        loginForm.setUsername(registerForm.getUsername());
        loginForm.setPassword(encryptedPassword);
        //用户登录返回对象
        int insert = 0;
        switch (userType) {
            case ADMIN:
                insert = adminServiceImpl.register(loginForm);
                break;
            case STUDENT:
                insert = studentSeiveceImpl.register(loginForm);
                break;
            case TEACHER:
                insert = teacherSeiveceImpl.register(loginForm);
                break;
            default:
                return JsonDate.fail("错误类型", 1);
        }
        if (insert > 0) {
            return JsonDate.success("注册成功",0);
        } else {
            return JsonDate.fail("注册失败", 1);
        }
    }


    /**
     * 查询用户详情
     * @return
     */
    @Override
    public UserInfoDTO userInfo() {
        int loginUserId = LoginUserInfoUtils.getLoginUserId();
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        switch (LoginUserInfoUtils.getLoginUserType()) {
            case ADMIN:
                Admin admin = adminServiceImpl.getById(loginUserId);
                userInfoDTO.setUserId(admin.getId());
                userInfoDTO.setUsername(admin.getAdminName());
                userInfoDTO.setUserType(UserType.ADMIN);
                return userInfoDTO;
            case STUDENT:
                Student student = studentSeiveceImpl.getById(loginUserId);
                userInfoDTO.setUserId(student.getId());
                userInfoDTO.setUsername(student.getStudentName());
                userInfoDTO.setUserType(UserType.STUDENT);
                return userInfoDTO;
            case TEACHER:
                Teacher teacher = teacherSeiveceImpl.getById(loginUserId);
                userInfoDTO.setUserId(teacher.getId());
                userInfoDTO.setUsername(teacher.getTeacherName());
                userInfoDTO.setUserType(UserType.TEACHER);
                return userInfoDTO;
            default:
                return null;
        }
    }
}
